package com.carlos.company.security.filter;

import com.carlos.company.service.SysRoleResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.List;

/**
 * @author 李健成
 * @date 2021/10/15
 */

@Component
public class MySecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    @Autowired
    private SysRoleResourceService sysRoleResourceService;

    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        String url = ((FilterInvocation) o).getHttpRequest().getRequestURI();
        String method = ((FilterInvocation) o).getHttpRequest().getMethod();
        List<String> roles = sysRoleResourceService.listRoleByResource(url);
        if (CollectionUtils.isEmpty(roles)) {
            return null;
        } else {
            return SecurityConfig.createList(roles.toArray(new String[0]));
        }
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return FilterInvocation.class.isAssignableFrom(aClass);
    }

}